﻿using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class EnemyBoardView : MonoBehaviour
{
    [SerializeField] private Transform slotParent; // 槽位父物体，用于动态生成槽位或获取子物体槽位
    [SerializeField] private int maxSlots = 5; // 最大槽位数

    public List<EnemyView> EnemyViews { get; private set; } = new();

    private List<Transform> slots = new List<Transform>();
    private Queue<Transform> availableSlots = new Queue<Transform>();

    private void Awake()
    {
        InitializeSlots();
    }

    private void InitializeSlots()
    {
        slots.Clear();
        availableSlots.Clear();

        // 如果slotParent已有子物体，把它们当槽位
        if (slotParent.childCount > 0)
        {
            foreach (Transform child in slotParent)
            {
                slots.Add(child);
                availableSlots.Enqueue(child);
            }
        }
        else
        {
            // 否则根据maxSlots动态创建槽位空物体，按一定规则布局
            float spacing = 2f; // 槽位间距
            for (int i = 0; i < maxSlots; i++)
            {
                GameObject slotGO = new GameObject($"Slot_{i}");
                slotGO.transform.parent = slotParent;
                slotGO.transform.localPosition = new Vector3(i * spacing, 0, 0);
                slots.Add(slotGO.transform);
                availableSlots.Enqueue(slotGO.transform);
            }
        }
    }

    public void AddEnemy(Enemy enemy)
    {
        if (availableSlots.Count == 0)
        {
            Debug.LogError("没有空插槽可以放置敌人了！");
            return;
        }

        Transform slot = availableSlots.Dequeue();

        EnemyView enemyView = EnemyViewCreator.Instance.CreateEnemyView(enemy, slot);
        enemyView.transform.SetParent(slot, false); // 保持槽位相对位置
        EnemyViews.Add(enemyView);
    }

    public IEnumerator RemoveEnemy(EnemyView enemyView)
    {
        if (EnemyViews.Remove(enemyView))
        {
            Transform slot = enemyView.transform.parent;
            availableSlots.Enqueue(slot); // 释放槽位

            Tween tween = enemyView.transform.DOScale(Vector3.zero, 0.05f);
            yield return tween.WaitForCompletion();

            Destroy(enemyView.gameObject);
        }
        yield return null;
        if (EnemyViews.Count == 0)
        {
            WinGA ga = new WinGA(EnemySystem.Instance.id);
            ActionSystem.Instance.AddReaction(ga);
        }
    }
}
